//
//  SelectDesignerViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/19.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SelectDesignerViewController.h"

#import "DesignerListCell.h"
#import "YourDesignerModel.h"

@interface SelectDesignerViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic,strong)  NSMutableArray * YourDesigner;
@property (nonatomic, strong) UIView *moveLine;
@property (nonatomic, strong) UIButton *selectBtn;

@property (nonatomic,strong)  NSMutableArray  * dataArray;

@property (nonatomic,assign)  NSInteger       page;
@property (nonatomic,assign)  NSInteger       current_page;

@property (nonatomic,assign)  NSInteger       selectIndex;

@end

@implementation SelectDesignerViewController

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择设计师";
    _YourDesigner = [NSMutableArray array];
    _selectIndex = -1;
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(59))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    [self refreshTableView];
    [self getYourDesignerData];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(59), SCREEN_WIDTH, ScreenX375(59))];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(8), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
    sureBtn.backgroundColor = ThemeColor;
    sureBtn.layer.cornerRadius = ScreenX375(22);
    sureBtn.clipsToBounds = YES;
    [sureBtn setTitle:@"确 定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = Kfont(16);
    [sureBtn addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:sureBtn];
}

- (void)sure {
    NSString *shopId = @"";
    NSString *userId = @"";
    if (_selectIndex >= 200) {
        DesignListDataModel *model = _dataArray[_selectIndex - 200];
        shopId = model.Id;
        userId = model.user_id;
    }else if (_selectIndex >= 100) {
        YourDesignerModel *model = self.YourDesigner[_selectIndex - 100];
        shopId = model.store_id;
        userId = model.user_id;
    }
    if (_chooseDesignerClick) {
        _chooseDesignerClick(shopId,userId);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)selectDesign:(UIButton *)button {
    _selectIndex = button.tag - 300;
    [_tableView reloadData];
}

-(void)getYourDesignerData{
    NSDictionary *parameter = @{@"token":kNSUDefaultReadKey(@"token")};
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/cooperate_designer",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSError *error = nil;
            for(NSDictionary *dict in successResponse[@"data"]){
                YourDesignerModel *model = [[YourDesignerModel alloc] initWithDictionary:dict error:&error];
                model.store_id = dict[@"id"];
                [self.YourDesigner addObject:model];
            }
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

-(void)refreshTableView
{
    /** 为了避免 block 的循环引用导致内存泄漏  要使用__weakSelf 来代替self */
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.current_page = 1;
        [weakSelf requestData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestMoreData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

-(void)requestData
{
    NSString *url = [NSString stringWithFormat:@"%@app/shop_index",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":@"1",@"longitude":kNSUDefaultReadKey(@"longitude"),@"latitude":kNSUDefaultReadKey(@"latitude"),@"label":@"水印设计",@"orderBy":@"default desc"};
    
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self.tableView.mj_header endRefreshing];
            NSError *error;
            
            [self.dataArray removeAllObjects];
            self.page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                DesignListDataModel *model = [[DesignListDataModel alloc] initWithDictionary:dic error:&error];
                if (model != nil) {
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_header endRefreshing];
        [HttpManager showFail];
    }];
}

-(void)requestMoreData
{
    self.current_page++;
    NSString *url = [NSString stringWithFormat:@"%@app/shop_index",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":[NSNumber numberWithInteger:self.current_page],@"longitude":kNSUDefaultReadKey(@"longitude"),@"latitude":kNSUDefaultReadKey(@"latitude"),@"label":@"水印设计",@"orderBy":@"default desc"};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self.tableView.mj_footer endRefreshing];
            NSError *error;
            // 成功
            self.page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                DesignListDataModel *model = [[DesignListDataModel alloc] initWithDictionary:dic error:&error];
                if (model != nil) {
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_footer endRefreshing];
        [HttpManager showFail];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellId = @"CooperatedCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            
            _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(100))];
            _scrollView.showsVerticalScrollIndicator = false;
            _scrollView.showsHorizontalScrollIndicator = false;
            _scrollView.delegate = self;
            _scrollView.contentSize = CGSizeMake(ScreenX375(17) + self.YourDesigner.count * ScreenX375(75), 0);
            [cell addSubview:_scrollView];
        }
        for (UIView *subView in _scrollView.subviews) {
            [subView removeFromSuperview];
        }
        for (int i = 0; i < self.YourDesigner.count; i++) {
            YourDesignerModel *model = self.YourDesigner[i];
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(14) + i * ScreenX375(75), 0, ScreenX375(64), ScreenX375(64))];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.person_img] placeholderImage:nil options:SDWebImageRetryFailed];
            imageView.layer.cornerRadius = ScreenX375(32);
            imageView.clipsToBounds = YES;
            if (i == _selectIndex - 100) {
                imageView.layer.borderColor = ThemeColor.CGColor;
                imageView.layer.borderWidth = 1;
            }else {
                imageView.layer.borderWidth = 0;
            }
            [_scrollView addSubview:imageView];
            
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(14) + i * ScreenX375(75), ScreenX375(70), ScreenX375(64), ScreenX375(18))];
            nameLabel.text = model.realname;
            nameLabel.font = Kfont(14);
            nameLabel.textAlignment = NSTextAlignmentCenter;
            if (i == _selectIndex - 100) {
                nameLabel.textColor = ThemeColor;
            }else {
                nameLabel.textColor = REXADECIMALCOLOR(@"#333333");
            }
            [_scrollView addSubview:nameLabel];
            
            UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(14) + i * ScreenX375(75), 0, ScreenX375(64), ScreenX375(100))];
            selectBtn.backgroundColor = [UIColor clearColor];
            selectBtn.tag = 400 + i;
            [selectBtn addTarget:self action:@selector(selectDesign:) forControlEvents:UIControlEventTouchUpInside];
            [_scrollView addSubview:selectBtn];
        }
        return cell;
    }else {
        DesignerListCell *cell = [DesignerListCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.designListDataModel = _dataArray[indexPath.row];
        if (indexPath.row == _selectIndex - 200) {
            [cell cellIsSelect:YES];
        }else {
            [cell cellIsSelect:NO];
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        _selectIndex = 200 + indexPath.row;
        [_tableView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return ScreenX375(100);
    }
    return ScreenX375(110);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return ScreenX375(53);
    }
    return ScreenX375(58);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(53))];
        view.backgroundColor = [UIColor whiteColor];
        
        UIView *rline = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
        rline.backgroundColor = ThemeColor;
        [view addSubview:rline];
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(300), ScreenX375(24))];
        noteLabel.text = @"合作过的设计师";
        noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        noteLabel.font = Kfont(18);
        [view addSubview:noteLabel];
        
        return view;
    }else {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(58))];
        bgView.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(10), SCREEN_WIDTH, ScreenX375(48))];
        view.backgroundColor = [UIColor whiteColor];
        [bgView addSubview:view];
        
        UIView *rline = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
        rline.backgroundColor = ThemeColor;
        [view addSubview:rline];
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(300), ScreenX375(24))];
        noteLabel.text = @"设计师列表";
        noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        noteLabel.font = Kfont(18);
        [view addSubview:noteLabel];
        
//        NSArray *noteArr = @[@"综合",@"距离",@"等级",@"信用",@"好评"];
//        for (int i = 0; i < noteArr.count; i++) {
//            UIButton *typeBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / noteArr.count, ScreenX375(48), SCREEN_WIDTH / noteArr.count, ScreenX375(30))];
//            [typeBtn setTitle:noteArr[i] forState:UIControlStateNormal];
//            [typeBtn setTitleColor:ThemeColor forState:UIControlStateSelected];
//            [typeBtn setTitleColor:REXADECIMALCOLOR(@"#999999") forState:UIControlStateNormal];
//            typeBtn.titleLabel.font = Kfont(14);
//            typeBtn.tag = 100 + i;
//            if (i == 0) {
//                typeBtn.selected = YES;
//                _selectBtn = typeBtn;
//            }
//            [typeBtn addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
//            [view addSubview:typeBtn];
//        }
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(48) - 0.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = REXADECIMALCOLOR(@"#eeeeee");
        [view addSubview:line];
        
//        self.moveLine = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / noteArr.count - ScreenX375(30)) / 2, ScreenX375(78) - 1.5, ScreenX375(30), 1.5)];
//        self.moveLine.backgroundColor = ThemeColor;
//        [view addSubview:self.moveLine];
        
        return bgView;
    }
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    [UIView animateWithDuration:0.3 animations:^{
        self.moveLine.frame = CGRectMake((SCREEN_WIDTH / 5 - ScreenX375(30)) / 2 + (button.tag - 100) * SCREEN_WIDTH / 5, ScreenX375(78) - 1.5, ScreenX375(30), 1.5);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
